from django.shortcuts import render

# Create your views here.
from django.views import View
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from rest_framework.views import APIView
from rest_framework_jwt.views import ObtainJSONWebToken



from users import serializers
from users.models import User
from users.serializers import CreateUserSerializer, UserDetailSerializer


class TestViews(View):
    def get(self, request):
        return render(request, 'test.html')


# 用户名个数
class UsernameCountView(APIView):
    # 请求方式： GETusernames / (?P < username >\w{5, 20}) / count /
    def get(self,request,username):

        # 查询数据库 获取用户的个数 Queryset
        count = User.objects.filter(username=username).count()
        data ={
            'username': username,
            'count': count,
        }
        # print('ok')
        return Response(data)


# 注册前查询手机号是否注册
class UsermobileCountView(APIView):
    def get(self,request,mobile):

        # 查询数据库获得手机号的个数
        count = User.objects.filter(mobile=mobile).count()
        data ={
            'mobile':mobile,
            'count':count,
        }
        return Response(data)


# 创建用户
class CreateUserView(CreateAPIView):

    serializer_class = CreateUserSerializer


class MyObtainJSONWebToken(ObtainJSONWebToken):
    '''登陆接口'''
    pass


class UserDetailView(RetrieveAPIView):
    """用户详情"""
    serializer_class = serializers.UserDetailSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user


class EmailView(UpdateAPIView):
    """
    修改用户邮箱（修改用户的邮箱字段）
    """
    permission_classes = [IsAuthenticated]
    serializer_class = serializers.EmailSerializer

    # 重写GenericAPIView的方法，指定要修改的是哪一条用户数据
    def get_object(self):
        return self.request.user   #  修改的具体用户